package views;

import java.awt.Container;
import java.awt.Cursor;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.Icon;
import javax.swing.JEditorPane;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.Document;

/**
 *
 * @author eagle
 */
public class AyudaIFrame extends JInternalFrame {

    public AyudaIFrame() {
        super("Manual de usuario", true, true, true, true);

        setFrameIcon((Icon) UIManager.get(""));
        setBounds(200, 25, 400, 400);
        HtmlPane html = new HtmlPane();
        setContentPane(html);
    }
}

class HtmlPane extends JScrollPane implements HyperlinkListener {

    JEditorPane html;

    public HtmlPane() {
        try {
            URL url = getClass().getResource("/views/resources/manual.html");
            html = new JEditorPane(url);
            html.setEditable(false);
            html.addHyperlinkListener(this);
            html.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES,
                    Boolean.TRUE);
            JViewport vp = getViewport();
            vp.add(html);
        } catch (MalformedURLException e) {
            System.out.println("URL mal: " + e);
        } catch (IOException e) {
            System.out.println("IOException: " + e);
        }
    }

    public void hyperlinkUpdate(HyperlinkEvent e) {
        if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
            linkActivated(e.getURL());
        }
    }

    protected void linkActivated(URL u) {
        Cursor c = html.getCursor();
        Cursor waitCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
        html.setCursor(waitCursor);
        SwingUtilities.invokeLater(new PageLoader(u, c));
    }

    class PageLoader implements Runnable {

        PageLoader(URL u, Cursor c) {
            url = u;
            cursor = c;
        }

        public void run() {
            if (url == null) {
                html.setCursor(cursor);
                Container parent = html.getParent();
                parent.repaint();
            } else {
                Document doc = html.getDocument();
                try {
                    html.setPage(url);
                } catch (IOException e) {
                    html.setDocument(doc);
                    getToolkit().beep();
                } finally {
                    url = null;
                    SwingUtilities.invokeLater(this);
                }
            }
        }
        URL url;
        Cursor cursor;
    }
}
